package com.yanqu.road.server.gameplayer.module.npc;

import com.yanqu.road.entity.DataStatus;
import com.yanqu.road.entity.activity.eggs.EggsUserData;
import com.yanqu.road.entity.config.npc.NpcTalkInfo;
import com.yanqu.road.entity.config.npc.NpcTradeInfo;
import com.yanqu.road.entity.enums.eChannelType;
import com.yanqu.road.entity.enums.eGamePlayerEventType;
import com.yanqu.road.entity.enums.eLogMoneyType;
import com.yanqu.road.entity.enums.eSystemId;
import com.yanqu.road.entity.log.LogNpcTalk;
import com.yanqu.road.entity.npc.UserNpcGangfen;
import com.yanqu.road.entity.npc.UserNpcTalk;
import com.yanqu.road.entity.npc.UserNpcTrade;
import com.yanqu.road.entity.servercenter.ServerInfo;
import com.yanqu.road.logic.bussiness.player.UserNpcEventBussiness;
import com.yanqu.road.logic.config.ChannelConfig;
import com.yanqu.road.pb.npc.NpcEventProto;
import com.yanqu.road.server.GameServer;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.activity.eggs.EggsActivityModule;
import com.yanqu.road.server.gameplayer.module.base.GeneralModule;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.ServerListMgr;
import com.yanqu.road.server.manger.activity.eggs.EggsActivityConfig;
import com.yanqu.road.server.manger.activity.eggs.EggsActivityMgr;
import com.yanqu.road.server.manger.config.NpcConfigMgr;
import com.yanqu.road.server.manger.config.SystemOpenMgr;
import com.yanqu.road.server.manger.log.AutoLogMgr;
import com.yanqu.road.server.manger.log.LogMgr;
import com.yanqu.road.server.pb.NpcPb;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.Protocol;
import com.yanqu.road.utils.property.PropertyHelper;

import java.util.Date;

public class NpcEventModule extends GeneralModule {

    private UserNpcTalk userNpcTalk;

    private UserNpcTrade userNpcTrade;

    private UserNpcGangfen userNpcGangfen;

    public NpcEventModule(GamePlayer player) {
        super(player);
    }


    //获取npc对话奖励
    public int getNpcTalkReward(int choose){
        if(userNpcTalk.isGetReward()){
            return GameErrorCode.E_NPC_TALK_EVENT_IS_GETREWARD;
        }
        int eventId = userNpcTalk.getEventId();
        NpcTalkInfo npcTalkInfo = null;
        if(EggsActivityMgr.isActivityInShowTime()){//有联动时，用活动配置来
            EggsActivityConfig eggsActivityConfig = EggsActivityMgr.getEggsActivityConfig();
            if(null != eggsActivityConfig){
                npcTalkInfo = eggsActivityConfig.getNpcTalkInfo(eventId);
            }
        }
        if(null == npcTalkInfo){
            npcTalkInfo = NpcConfigMgr.getNpcTalkInfo(eventId);
        }
        if (npcTalkInfo == null) {
            return GameErrorCode.E_EVENT_CONFIG_NO_FOUND;
        }
        NpcEventProto.GetNpcTalkRewardRespMsg.Builder respMsg = NpcEventProto.GetNpcTalkRewardRespMsg.newBuilder();

        userNpcTalk.setGetReward(true);
        userNpcTalk.setStatus(1);
        String reward = "";

        if (npcTalkInfo.getType() == 1) {
            reward = npcTalkInfo.getReward();
        } else if (npcTalkInfo.getType() == 10) { //新增的选择事件
            int rightChoose = Integer.parseInt(npcTalkInfo.getExtendParam().split(";")[0].split("-")[0]);
            boolean isRight = choose - rightChoose == 1;
            String[] rewardList = npcTalkInfo.getReward().split("\\|");
            reward = isRight ? rewardList[0] : rewardList[1];

            respMsg.setRight(isRight);
        }
        respMsg.setReward(reward);

        player.getModule(CurrencyModule.class).addCurrency(reward, eLogMoneyType.NpcEvent,eLogMoneyType.NpcTalkEventGetReward);

        respMsg.setRet(0);
        player.sendPacket(Protocol.U_NPC_TALK_GET_REWARD, respMsg);

//        LogMgr.addLogNpcTalk(new LogNpcTalk(
//                player.getUserId(),
//                npcTalkInfo.getType(),
//                npcTalkInfo.getEventId(),
//                choose,
//                reward,
//                new Date()));

        AutoLogMgr.add(new LogNpcTalk(
                player.getUserId(),
                npcTalkInfo.getType(),
                npcTalkInfo.getEventId(),
                choose,
                reward,
                new Date()));

        //不刷新了，让定时器刷新，不然客户端会去掉气泡
//        npcLogicChange();
        return 0;
    }

    public String getNpcTradeNowReward() {
        if (userNpcTrade == null) {
            return "";
        }
        return userNpcTrade.getReward();
    }
    public int getNpcTradeReward(){
        if(userNpcTrade.isGetReward()){
            return GameErrorCode.E_NPC_TRADE_EVENT_IS_GETREWARD;
        }
        long tradeTime = NpcConfigMgr.getNpcTradeInfo(userNpcTrade.getEventId()).getTradeTime();
        if((userNpcTrade.getStatus() == 1 && System.currentTimeMillis() >= userNpcTrade.getRefreshTime() + tradeTime*1000)
                || userNpcTrade.getStatus() == 2){
            userNpcTrade.setGetReward(true);
            player.getModule(CurrencyModule.class).addCurrency(userNpcTrade.getReward(), eLogMoneyType.NpcEvent,eLogMoneyType.NpcTradeEventGetReward);
            //领取了奖励就刷新了
            npcLogicChange();
            player.notifyListener(eGamePlayerEventType.NpcTradeTimes.getValue(),1);
            return 0;
        }else{
            return GameErrorCode.E_NPC_TRADE_EVENT_NOT_OVER;
        }
    }

    //港风彩蛋领奖
    public int getNpcGaneFenReward(){
        if(!userNpcGangfen.isGetReward()){
            userNpcGangfen.setGetReward(true);
            player.getModule(CurrencyModule.class).addCurrency(userNpcGangfen.getReward(), eLogMoneyType.NpcEvent,eLogMoneyType.NpcGangfengEventGetReward);
            NpcEventProto.GetNpcGangFenRewardRespMsg.Builder respMsg = NpcEventProto.GetNpcGangFenRewardRespMsg.newBuilder();
            respMsg.setRet(0);
            respMsg.setReward(userNpcGangfen.getReward());
            player.sendPacket(Protocol.U_NPC_GANGFEN_GET_REWARD, respMsg);
            //领取了奖励就刷新了
            npcLogicChange();
            syncNpcGangfenEvent();
            return 0;
        }else{
            return GameErrorCode.E_NPC_GANGFENG_EVENT_IS_GETREWARD;
        }
    }

    //接受当前的任务
    public int npcTradeEventStock(){
        if(userNpcTrade.getStatus() != 0){
            return GameErrorCode.E_NPC_TRADE_EVENT_NOT_STOCK;
        }
        if(!player.getModule(CurrencyModule.class).removeCurrency(PropertyHelper.parseStringToProperty(userNpcTrade.getConsume()),eLogMoneyType.NpcEvent,eLogMoneyType.NpcTradeEventStock)){
            return GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
        }
        userNpcTrade.setStatus(1);
        userNpcTrade.setRefreshTime(System.currentTimeMillis());
        player.notifyListener(eGamePlayerEventType.DAY_FIRST_NPC_TRADE.getValue());
        syncNpcTradeEvent();
        return 0;
    }

    /**
     * 小玉自动贸易,没备货先备货,备货了就领奖
     * @return
     */
    public int autoTradeEvent() {
        int ret = npcTradeEventStock();
        if (ret != 0) {
            ret = getNpcTradeReward();
            if (ret == 0) {

            }
        }
        return ret;
    }

    //npc定时触发事件，刷新事件和事件状态变更
    public void npcLogicChange(){
        if(NpcConfigMgr.isNpcTalkRefreshTime(userNpcTalk)){
            newUserNpcTalk(userNpcTalk.getNo()+1);
        }
        npcTradeLogic();
        npcGangfenLogic();
    }

    //npc贸易的逻辑处理
    private void npcTradeLogic(){
        if(userNpcTrade == null){
            return;
        }
        //状态0等待备货会触发刷新
        if(userNpcTrade.getStatus() == 0){
            if(NpcConfigMgr.isNpcTradeRefreshTime(userNpcTrade)){
                //假如固定事件没有完成，就一直刷固定事件，刷到他完成为止，1.6.0修改
                if(NpcConfigMgr.isDefaultTradeInfo(userNpcTrade.getNo())){
                    newUserNpcTrade(userNpcTrade.getNo());
                }else{
                    newUserNpcTrade(userNpcTrade.getNo()+1);
                }
            }
        }
        //状态1贸易中会触发贸易结束等待领奖
        if(userNpcTrade.getStatus() == 1){
            NpcTradeInfo npcTradeInfo = NpcConfigMgr.getNpcTradeInfo(userNpcTrade.getEventId());
            if(System.currentTimeMillis() - userNpcTrade.getRefreshTime() >= (long)npcTradeInfo.getTradeTime() * 1000){
                userNpcTrade.setStatus(2);
                syncNpcTradeEvent();
            }
        }

        if(userNpcTrade.getStatus() == 2 && userNpcTrade.isGetReward()){
            newUserNpcTrade(userNpcTrade.getNo()+1);
        }

    }

    //npc贸易的逻辑处理
    private void npcGangfenLogic(){
        if(userNpcGangfen == null){
            return;
        }
        //时间到就直接刷了
        if(NpcConfigMgr.isNpcGangFenRefreshTime(userNpcGangfen)){
            newUserNpcGangfen(userNpcGangfen.getNo()+1);
        }
    }

    public void initUserNpcTalkEvent(){
        if (null == userNpcTalk) {
            newUserNpcTalk(1);
        }
    }

    public void initUserNpcTradeEvent(){
        if (null == userNpcTrade) {
            newUserNpcTrade(1);
        }
    }

    public void initUserGangfenEvent(){
        if (null == userNpcGangfen) {
            newUserNpcGangfen(1);
        }
    }

    private void newUserNpcTalk(int no){
        NpcTalkInfo npcTalkInfo = null;
        if(EggsActivityMgr.isActivityInShowTime()){//有联动时，用活动配置来
            EggsActivityConfig eggsActivityConfig = EggsActivityMgr.getEggsActivityConfig();
            if(null != eggsActivityConfig){
                EggsUserData eggsUserData = player.getModule(EggsActivityModule.class).getEggsUserData();
                if(null != eggsUserData) {
                    npcTalkInfo = eggsActivityConfig.getNpcTalkInfoByNo(eggsUserData);
                }
            }
        }
        if(null == npcTalkInfo) {
            npcTalkInfo = NpcConfigMgr.getNpcTalkInfoByNo(no);
        }
        UserNpcTalk temp = new UserNpcTalk();
        temp.setUserId(player.getUserId());
        temp.setNo(no);
        temp.setEventId(npcTalkInfo.getEventId());
        temp.setReward(npcTalkInfo.getReward());
        temp.setStatus(0);
        temp.setRefreshTime(System.currentTimeMillis());
        temp.setGetReward(false);
        if(null == userNpcTalk){
            temp.setInsertOption();
        }
        userNpcTalk = temp;
        syncNpcTalkEvent();
//        logger.error("刷新npc对话事件并且同步给客户端no:{}-userId:{}-event:{}",userNpcTalk.getNo(),player.getUserId(),userNpcTalk.getEventId());
    }

    private void newUserNpcTrade(int no){
        NpcTradeInfo npcTradeInfo = NpcConfigMgr.getNpcTradeInfoByNo(no);
        UserNpcTrade temp = new UserNpcTrade();
        temp.setUserId(player.getUserId());
        temp.setNo(no);
        temp.setEventId(npcTradeInfo.getEventId());
        temp.setConsume(npcTradeInfo.getConsume());
        temp.setReward(npcTradeInfo.getReward());
        temp.setStatus(0);
        temp.setRefreshTime(System.currentTimeMillis());
        temp.setGetReward(false);
        if(null == userNpcTrade){
            temp.setInsertOption();
        }
        userNpcTrade = temp;
        syncNpcTradeEvent();
    }

    private void newUserNpcGangfen(int no){
        NpcTradeInfo npcTradeInfo = NpcConfigMgr.getNpcGangfenInfoByNo();
        if (npcTradeInfo == null) {
            log.error("npcTradeInfo is Null ,no:{}", no);
            return;
        }
        UserNpcGangfen temp = new UserNpcGangfen();
        temp.setUserId(player.getUserId());
        temp.setNo(no);
        temp.setEventId(npcTradeInfo.getEventId());
        temp.setReward(npcTradeInfo.getReward());
        temp.setRefreshTime(System.currentTimeMillis());
        temp.setGetReward(false);
        if(null == userNpcGangfen){
            temp.setInsertOption();
        }
        userNpcGangfen = temp;
        syncNpcGangfenEvent();
    }

    @Override
    public boolean loadData() {
        userNpcTalk = UserNpcEventBussiness.getUserNpcTalk(player.getUserId());
        userNpcTrade = UserNpcEventBussiness.getUserNpcTrade(player.getUserId());
        userNpcGangfen = UserNpcEventBussiness.getUserNpcGangfen(player.getUserId());
        return true;
    }

    @Override
    public boolean afterLoadData() {
        if(SystemOpenMgr.systemOpen(player, eSystemId.NpcTalk.getValue())){
            initUserNpcTalkEvent();
        }
        if(SystemOpenMgr.systemOpen(player, eSystemId.NpcTrade.getValue())){
            initUserNpcTradeEvent();
        }
        if(SystemOpenMgr.systemOpen(player, eSystemId.NpcGangFeng.getValue())){
//            log.error("港风初始化{}",player.getUserId());
            initUserGangfenEvent();
        }
        return true;
    }


    @Override
    public boolean saveData() {
        if(null != userNpcTalk){
            if(userNpcTalk.getOp() == DataStatus.Insert){
                UserNpcEventBussiness.addUserNpcTalk(userNpcTalk);
            }else if(userNpcTalk.getOp() == DataStatus.Update){
                UserNpcEventBussiness.updateUserNpcTalk(userNpcTalk);
            }
        }

        if(null != userNpcTrade){
            if(userNpcTrade.getOp() == DataStatus.Insert){
                UserNpcEventBussiness.addUserNpcTrade(userNpcTrade);
            }else if(userNpcTrade.getOp() == DataStatus.Update){
                UserNpcEventBussiness.updateUserNpcTrade(userNpcTrade);
            }
        }

        if(null != userNpcGangfen){
            if(userNpcGangfen.getOp() == DataStatus.Insert){
                UserNpcEventBussiness.addUserNpcGangfen(userNpcGangfen);
            }else if(userNpcGangfen.getOp() == DataStatus.Update){
                UserNpcEventBussiness.updateUserNpcGangfen(userNpcGangfen);
            }
        }

        return true;
    }

    @Override
    public void afterLogin() {

    }

    @Override
    public void loginSendMsg() {
        if(null != userNpcTalk){
            syncNpcTalkEvent();
        }

        if(null != userNpcTrade){
            syncNpcTradeEvent();
        }

        if(null != userNpcGangfen){
            syncNpcGangfenEvent();
        }

        NpcEventProto.GangFengSystemMsg.Builder openMsg = NpcEventProto.GangFengSystemMsg.newBuilder();
        boolean useReview = false;
        int channelId = ServerListMgr.getChannelId(GameServer.getInstance().getServerId());
        if(eChannelType.isMainLandChannel(channelId)){
            ServerInfo serverInfo = ServerListMgr.getServerInfo(GameServer.getInstance().getServerId());
            if(null != serverInfo && serverInfo.getServerType() == ServerListMgr.SERVER_TYPE_REVIEW){//提审服用提审配置
                useReview = true;
            }
        }
        if(useReview){
            openMsg.setOpen(ChannelConfig.HONGKONG_WIND_OPEN_REVIEW == 1);
        }else {
            openMsg.setOpen(ChannelConfig.HONGKONG_WIND_OPEN == 1);
        }
        player.sendPacket(Protocol.U_GANGFEN_SYSTEM_SYNC, openMsg);
    }

    public void syncNpcTalkEvent(){
        NpcEventProto.NpcTalkEventMsg.Builder userMsg = NpcPb.parseNpcTalkEventMsg(userNpcTalk);
        player.sendPacket(Protocol.U_NPC_TALK_EVENT_SYNC, userMsg);
    }

    public void syncNpcTradeEvent(){
        NpcEventProto.NpcTradeEventMsg.Builder userMsg = NpcPb.parseNpcTradeEventMsg(userNpcTrade);
        player.sendPacket(Protocol.U_NPC_TRADE_EVENT_SYNC, userMsg);
    }

    public void syncNpcGangfenEvent(){
        NpcEventProto.NpcGangFenEventMsg.Builder userMsg = NpcPb.parseNpcGangfenEventMsg(userNpcGangfen);
        player.sendPacket(Protocol.U_NPC_GANGFEN_EVENT_SYNC, userMsg);
    }

}
